package servlets;

import helper.Helper;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import constants.AttributeConstants;
import constants.TasksConstants;
import myJDBC.myConnection;
import myJDBC.entities.Orders;
import myJDBC.lowLevel.Objects;
import myJDBC.lowLevel.Params;
import myJDBC.lowLevel.References;
import ejb.IRemoteLoginnedUserBean;

@WebServlet("/Order")
public class Order extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		int taskId=-9;
		if(request.getParameter("type")!=null){
			if(request.getParameter("type").equals("takeTask")){
				taskId=Integer.parseInt(request.getParameter("TaskId"));
				int userId= ((IRemoteLoginnedUserBean) request.getSession().getAttribute("userBean")).getObjectId();
				try {
					Orders.takeManualTask(userId, taskId);
				} catch (SQLException e) {
					e.printStackTrace();
				}				
			}			
		}		
		if(request.getParameter("typeTask")!=null){//put_line_task!!!!!!!!!!!!!!!
			taskId=Integer.parseInt(request.getParameter("TaskId"));
			PreparedStatement statement= null;	
			if(request.getParameter("typeTask").equals(TasksConstants.put_line_task)){
				try{
						
					
					
					int port =-1;
					int customer = -1;
					int porch =-1;
					int router =-1;
					String selectCust = //достаю заказчика через таску
							"select \"parent_id\" from \"objects\" where \"object_id\"= (select \"parent_id\" from \"objects\" where \"object_id\"=?)";
					statement = myConnection.dbConnection.prepareStatement(selectCust);
					statement.setInt(1, taskId);
					ResultSet rs = statement.executeQuery();
					if(rs.next())
						customer =rs.getInt(1);				
					
					ArrayList<Integer> porchs = References.returnIdObj(constants.AttributeConstants.ref_porch, customer);
					porch = porchs.get(0);
					ArrayList<Integer> routers = Objects.returnChildrens(porch);//error is here
					for(int i =0; i<routers.size();i++){
						if(Integer.parseInt(Objects.returnObjectTypeId(routers.get(i))) == constants.ObjectTypeConstants.router){
								router = routers.get(i);
								break;
						}
					}
					ArrayList<Integer> ports_and_cards = Objects.returnChildrens(router);
					ArrayList<Integer> ports = new ArrayList<Integer>(); 
					ArrayList<Integer> cards = new ArrayList<Integer>(); 
					for(int i =0; i<ports_and_cards.size();i++){
						if(Integer.parseInt(Objects.returnObjectTypeId(ports_and_cards.get(i))) == constants.ObjectTypeConstants.port)
							ports.add(ports_and_cards.get(i));
						else
							cards.add(ports_and_cards.get(i));
					}
					for(int i =0; i<ports.size();i++){
						if(References.retRefereces(ports.get(i)).size()==0){
							port =ports.get(i);
							break;
						}
					}
					if(port<0){
						ports = new ArrayList<Integer>(); 
						for(int i =0; i<cards.size();i++){
							if(port!=-1) break;
							ports = Objects.returnChildrens(cards.get(i));
							for(int j =0; j<ports.size();j++){
								if(References.retRefereces(ports.get(j)).size()==0){
									port =ports.get(j);
									break;
								}
							}
						}
					}			
					References.createReference(constants.AttributeConstants.ref_client_id, port, customer);//привязка
					Params.changeValueId(port, constants.AttributeConstants.status, constants.ListValueConstants.port_active);
					
					statement = myConnection.dbConnection.prepareStatement(//get parent
							"select \"parent_id\" from \"objects\" where \"object_id\"=?");
					statement.setInt(1, taskId);
					rs = statement.executeQuery();
					
					int order=-1;//cansel order
					if(rs.next())
						order =rs.getInt(1);
					if(order>0){
						String updateOrder =  
								"UPDATE \"params\" SET \"list_value_id\" = 29 WHERE \"object_id\"=? and \"list_value_id\"=28 and \"attribute_id\"=17";//17 orderstatus
						statement = myConnection.dbConnection.prepareStatement(updateOrder);
						statement.setInt(1, order);
						statement.executeUpdate();
					}
					String updateParam =  //complete task
							"UPDATE \"params\" SET \"list_value_id\" = 33 WHERE \"object_id\"=? and \"attribute_id\"=19";//19 manualtaskstatus
					statement = myConnection.dbConnection.prepareStatement(updateParam);
					statement.setInt(1, taskId);
					statement.executeUpdate();
					
					Orders.manualTaskDone(taskId);
				}catch(SQLException e){
					System.out.println(e.getMessage());
				}				
	
			}
			if(request.getParameter("typeTask").equals(TasksConstants.setup_cart_task)){//setup_cart_task!!!!!!!!!!!!!11
				try{					
					Integer portCount=Integer.parseInt(request.getParameter("count"));
					int porch = Helper.GetPorch(taskId);	
					int router = -9;
					if (myConnection.dbConnection != null) {
						try {
							String selectRouter = 	"select \"object_id\" from \"objects\" where \"parent_id\"=? and \"object_type_id\"=54 ";//54="router"
							statement = myConnection.dbConnection.prepareStatement(selectRouter);
							statement.setInt(1, porch);
							ResultSet rs = statement.executeQuery();
							while (rs.next()) {
								router = rs.getInt(1);
							}
						} catch (SQLException e) {
							System.out.println(e.getMessage());
						}finally {
							if (statement != null)
								statement.close();
						}
					}
					int cardId = Objects.createObject("card", "blabla", constants.ObjectTypeConstants.card, router);					
					Params.createParamVarchNumb(constants.AttributeTypeConstants.number, cardId, portCount.toString());

					for(Integer i=0;i<portCount;i++){
						int PortId = Objects.createObject("port"+i.toString(), i.toString(), constants.ObjectTypeConstants.port, cardId);
						Params.createParamArray(constants.AttributeConstants.status, PortId, constants.ListValueConstants.port_available);
					}	
					
					String updateParam =  //complete task
							"UPDATE \"params\" SET \"list_value_id\" = 33 WHERE \"object_id\"=?  and \"attribute_id\"=19";
					statement = myConnection.dbConnection.prepareStatement(updateParam);
					statement.setInt(1, taskId);
					statement.executeUpdate();	
					
					ArrayList<Integer> next_task = References.returnIdObj(AttributeConstants.ref_next_task, taskId);
					String updateNext=  //init next task
							"UPDATE \"params\" SET \"list_value_id\" = 31 WHERE \"object_id\"=?  and \"attribute_id\"=19 ";
					statement = myConnection.dbConnection.prepareStatement(updateNext);
					statement.setInt(1, next_task.get(0));
					statement.executeUpdate();	
					
					Orders.manualTaskDone(taskId);
				}catch(SQLException e){
					System.out.println(e.getMessage());
				}			

			}
			if(request.getParameter("typeTask").equals(TasksConstants.setup_router_task)){//setup_router_task
				try{
					String descr=request.getParameter("descr");
					int portCount=Integer.parseInt(request.getParameter("count"));
					int porch = Helper.GetPorch(taskId);				
					int routerId = Objects.createObject("router", descr, constants.ObjectTypeConstants.router, porch);
					//insert date here later
								
					for(Integer i=0;i<portCount;i++){
						int PortId = Objects.createObject("port", i.toString(), constants.ObjectTypeConstants.port, routerId);
						Params.createParamArray(constants.AttributeConstants.status, PortId, constants.ListValueConstants.port_available);
					}	
					
					String updateParam =  //complete task
							"UPDATE \"params\" SET \"list_value_id\" = 33 WHERE \"object_id\"=? and \"attribute_id\"=19";
					statement = myConnection.dbConnection.prepareStatement(updateParam);
					statement.setInt(1, taskId);
					statement.executeUpdate();	
					
					ArrayList<Integer> next_task = References.returnIdObj(AttributeConstants.ref_next_task, taskId);
					//exec next auto-task
					Helper.CheckFreePort(next_task.get(0));	
					
					Orders.manualTaskDone(taskId);
				}catch(SQLException e){
					System.out.println(e.getMessage());
				}			
			}
		}
		response.sendRedirect("privateOffice");
	}

	 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 doGet(request,response);
	}

	 
}
